﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

/// <summary>
/// myLog 的摘要说明
/// </summary>
public class MyLog
{
    HttpContext context;

    public MyLog(HttpContext context)
    {
        this.context = context;
    }

    public void writeLog(String str)
    {
        string logName = DateTime.Today.ToString("yyyy-MM-dd");
        string logDirectPath = context.Server.MapPath("~/log");
        string filePath = logDirectPath + "\\" + logName + ".txt";

        if (Directory.Exists(logDirectPath) == false)
        {
            Directory.CreateDirectory(logDirectPath);
        }

        using (FileStream fs = new FileStream(filePath, FileMode.Append))
        {
            string logStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " : " + str + "\r\n";
            byte[] buffer = Encoding.UTF8.GetBytes(logStr);
            fs.Write(buffer, 0, buffer.Length);
        }
    }

    /// <summary>
    /// 日志老化
    /// </summary>
    public void burn()
    {
        try
        {
            JToken sendConf = (JToken)JsonConvert.DeserializeObject(File.ReadAllText(context.Server.MapPath("../Conf/FileSenderConf.json")));
            JToken ReceiveConf = (JToken)JsonConvert.DeserializeObject(File.ReadAllText(context.Server.MapPath("../Conf/FileReceiveConf.json")));

            int sendSaveDays = Convert.ToInt32(sendConf["logSavingDays"]);
            int receiveSaveDays = Convert.ToInt32(ReceiveConf["logSavingDays"]);

            int saveDays = Math.Max(sendSaveDays, receiveSaveDays);

            string[] logFiles = Directory.GetFiles(context.Server.MapPath("~/log"));
            foreach (string logFile in logFiles)
            {
                if (File.Exists(logFile) && File.GetCreationTime(logFile) < DateTime.Now.AddDays(0 - saveDays))
                {
                    File.Delete(logFile);
                }
            }
        }
        catch (Exception ex)
        {
            writeLog(ex.Message);
        }


    }
}